package com.lvy.hczn.front.business.service.impl;

import cn.hutool.core.thread.ThreadUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lvy.hczn.front.business.common.CacheConstants;
import com.lvy.hczn.front.business.common.Constants;
import com.lvy.hczn.front.business.service.*;
import com.lvy.hczn.front.common.utils.DictUtils;
import com.lvy.hczn.front.system.domain.business.*;
import com.lvy.hczn.front.business.dto.Param;
import com.lvy.hczn.front.business.mapper.DeliveryOrderDetailMapper;
import com.lvy.hczn.front.common.core.redis.RedisCache;
import com.lvy.hczn.front.common.exception.UtilException;
import com.lvy.hczn.front.system.service.WarehouseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class DeliveryOrderDetailServiceImpl extends ServiceImpl<DeliveryOrderDetailMapper, DeliveryOrderDetail> implements DeliveryOrderDetailService {

    @Autowired
    private PurchaseOrderDetailService purchaseOrderDetailService;

    @Autowired
    private DeliveryOrderService deliveryOrderService;

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private PurchaseOrderService purchaseOrderService;

    @Autowired
    private WarehousingEntryService warehousingEntryService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 取货单查询采购明细，当明细为空时，认为处理完，则更新状态为完成
     *
     * @param param
     * @return java.util.List<com.lvy.hczn.model.order.PurchaseOrderDetail>
     * @author yw
     * @date 2022-04-13 16:40:31
     */
    @Override
    public List<PurchaseOrderDetail> entryByDeliverCode(Param param) throws Exception {
        List<String> purchaseCodes = super.listObjs(Wrappers.<DeliveryOrderDetail>lambdaQuery().select(DeliveryOrderDetail::getPurchaseOrderCode).eq(DeliveryOrderDetail::getDeliveryOrderCode, param.getDeliveryOrderCode()), Object::toString);
            /*DeliveryOrderDetail deliveryOrderDetail = deliveryOrderDetailService.getOne(Wrappers.<DeliveryOrderDetail>lambdaQuery().eq(DeliveryOrderDetail::getDeliveryOrderCode, param.getDeliveryOrderCode()));
            if (deliveryOrderDetail == null) {
                return ResultUtil.failed("取货单信息为空");
            }*/
        if (purchaseCodes.isEmpty()) {
            throw new UtilException("取货单信息为空");
        }

        //1. 根据包裹编号查询对应的采购单详情 BG开头
        //2. 采购单详情里面的货箱编码 查询 其他的待入库的采购单详情 status = 0

        List<String> purchaseCodes2 = new ArrayList<>();
        String bgPrefix = DictUtils.getDictValue(com.lvy.hczn.front.common.constant.Constants.SYS_DICT_ORDER_TYPE, com.lvy.hczn.front.common.constant.Constants.SYS_DICT_ORDER_TYPE_BG);

        List<PurchaseOrderDetail> list = new ArrayList<>();
        for (String purchaseCode : purchaseCodes) {
            if(purchaseCode.startsWith(bgPrefix)){
                List<PurchaseOrderDetail> listBags = purchaseOrderDetailService.selectByPurchase(purchaseCodes, Constants.ENTRY_ING, param.getTempNum());
                for (PurchaseOrderDetail listBag : listBags) {
                    List<PurchaseOrderDetail> details =  purchaseOrderDetailService.selectByBoxCode(listBag.getBoxCode(),Constants.ENTRY_ING,null);
                    list.addAll(details);
                }
            }else{
                // 过滤不是包裹的采购单
                purchaseCodes2.add(purchaseCode);
            }
        }

//        List<PurchaseOrderDetail> list = purchaseOrderDetailService.list(Wrappers.<PurchaseOrderDetail>lambdaQuery().in(PurchaseOrderDetail::getPurchaseOrderCode, purchaseCodes).eq(PurchaseOrderDetail::getStatus, MqConstants.ENTRY_ING));
        if(!purchaseCodes2.isEmpty()){
            List<PurchaseOrderDetail> list2 = purchaseOrderDetailService.selectByPurchase(purchaseCodes2, Constants.ENTRY_ING, param.getTempNum());
            list.addAll(list2);
        }

        if (list.isEmpty()) {
            List<PurchaseOrderDetail> listAll = new ArrayList<>();
            //当前温区查询为空时，查询整个取货单，
            if (param.getTempNum() != null) {
                listAll = purchaseOrderDetailService.selectByPurchase(purchaseCodes, Constants.ENTRY_ING, null);
            }
            if (listAll.isEmpty() || param.getTempNum() == null) {
                String key = CacheConstants.REDIS_KEY_SOCKET_CLIENT + ":" + param.getUpOrDownPolicy().getClientId() + ":deliverOrderCode";
                redisCache.del(key);
                //采购入库根据温区空箱出库第一次进入页面，根据温区出库空箱，之后根据离开缓存位出库，没有记录则删除
                redisCache.del(CacheConstants.REDIS_KEY_SOCKET_CLIENT + ":" + param.getUpOrDownPolicy().getClientId() + ":deliverOrderCode:done");
                DeliveryOrder deliveryOrder = deliveryOrderService.getOne(Wrappers.<DeliveryOrder>lambdaQuery().eq(DeliveryOrder::getDeliveryOrderCode, param.getDeliveryOrderCode()));
                if (deliveryOrder != null) {
                    deliveryOrder.setStatus(Constants.DELIVERY_ORDER_STATUS_TWO);
                    if (deliveryOrderService.updateById(deliveryOrder)) {
                        commitToPlatform(deliveryOrder);
                    }
                }
            }
        } else {
            /*采购单非放到地平仓，则异常提示，即：登录的是地平仓电脑，扫的采购单是入立体仓的，则提示异常*/
            PurchaseOrderDetail purchaseOrderDetail = list.get(0);
            if (param.getBigProduct() != null && param.getBigProduct().equals(com.lvy.hczn.front.common.constant.Constants.GOODS_COLLECT_YES)) {
                if (!purchaseOrderDetail.getBigProduct().equals(com.lvy.hczn.front.common.constant.Constants.GOODS_COLLECT_YES)) {
                    throw new UtilException("单据商品为非大件物品，不能入此仓库！");
                }
            } else if (param.getBigProduct() != null && param.getBigProduct().equals(com.lvy.hczn.front.common.constant.Constants.GOODS_COLLECT_NO)) {
                if (!purchaseOrderDetail.getBigProduct().equals(com.lvy.hczn.front.common.constant.Constants.GOODS_COLLECT_NO)) {
                    throw new UtilException("单据商品为大件物品，不能入此仓库！");
                }
            }

            String key = CacheConstants.REDIS_KEY_SOCKET_CLIENT + ":" + param.getUpOrDownPolicy().getClientId() + ":deliverOrderCode";
            if (redisCache.get(key) == null) {
                redisCache.set(key, param.getDeliveryOrderCode(), 3, TimeUnit.DAYS);
            }
        }
        return list;
    }

    /**
     * 入库单同步到平台
     * 增加包裹推送
     * @param deliveryOrder
     * @return void
     * @author yw
     * @date 2023-08-24 16:54:00
     */
    public void commitToPlatform(DeliveryOrder deliveryOrder) {
        WarehousingEntry warehousingEntry = new WarehousingEntry();
        warehousingEntry.setEntryCode(deliveryOrder.getDeliveryOrderCode());
        warehousingEntry.setServiceCode(deliveryOrder.getServiceCode());
        warehousingEntryService.commitToPlatform(warehousingEntry, false, true);
    }

    /**
     * 配送单生成取货单扫码入库，理论上可以直接用配送单，仓库项目先做的，懒得改
     *
     * @param purchaseOrderInfo
     * @return void
     * @author yw
     * @date 2023-06-04 12:13:23
     */
    @Override
    @Transactional
    @Deprecated
    public void generateDeliver(PurchaseOrder purchaseOrderInfo) {
        String warehouseCode = warehouseService.selectLocalWarehouseFront().getWarehouseCode();
        List<PurchaseOrderDetail> list = purchaseOrderInfo.getList();
        DeliveryOrder deliveryOrder = new DeliveryOrder();
        deliveryOrder.setDeliveryOrderCode(purchaseOrderInfo.getDeliveryCode());
        deliveryOrder.setServiceType(purchaseOrderInfo.getServiceType());
        deliveryOrder.setServiceCode(purchaseOrderInfo.getServiceCode());
        deliveryOrder.setWarehouseCode(warehouseCode);
        deliveryOrder.setPurchaserId(purchaseOrderInfo.getCreateBy());
        deliveryOrder.setSupplierId(purchaseOrderInfo.getSupplierCode());
        deliveryOrder.setSourceId(purchaseOrderInfo.getSourceId());
        deliveryOrder.setStatus("0");
        deliveryOrder.setType("0");
        for (PurchaseOrderDetail detail : list) {
            DeliveryOrderDetail deliveryOrderDetail = new DeliveryOrderDetail();
            deliveryOrderDetail.setDeliveryOrderCode(deliveryOrder.getDeliveryOrderCode());
            deliveryOrderDetail.setWarehouseCode(warehouseCode);
            deliveryOrderDetail.setPurchaseOrderCode(detail.getPurchaseOrderCode());
            deliveryOrderDetail.setSupplierCode(detail.getSupplierCode());
            deliveryOrderDetail.setNumber(detail.getPurchaseQuantity());
            deliveryOrderDetail.setStatus("0");
            deliveryOrderDetail.setSourceId(detail.getSourceId());
            deliveryOrderDetail.setBoxCode(detail.getBoxCode());
            deliveryOrderDetail.setDeliveryTime(LocalDateTime.now());
            //箱为单位
            deliveryOrderDetail.setDeliveryNumber(1);
            super.save(deliveryOrderDetail);
        }
        deliveryOrderService.save(deliveryOrder);
        LambdaUpdateWrapper<PurchaseOrder> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(PurchaseOrder::getPurchaseOrderCode, purchaseOrderInfo.getPurchaseOrderCode()).set(PurchaseOrder::getDeliveryStatus, "1");
        purchaseOrderService.update(updateWrapper);
    }
}
